﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class PrefabLightmapData : MonoBehaviour
{
	[System.Serializable]
	struct RendererInfo
	{
		public Renderer 	renderer;
		public int 			lightmapIndex;
		public Vector4 		lightmapOffsetScale;
	}

	[SerializeField]
	RendererInfo[]	m_RendererInfo;
    //[SerializeField]
    //Texture2D[] m_Lightmaps;

    /// <summary>
    /// 每个挂有PrefabLightmapData的GameObject，他们的lightmap将不影响现有的lightmap，合并进去
    /// </summary>
    void Start ()
	{
		Reset ();
	}

	public void Reset() {
		if (m_RendererInfo == null || m_RendererInfo.Length == 0)
			return;

        //List<LightmapData> lightmapDataList = new List<LightmapData>();
        //foreach (Texture2D texture2d in m_Lightmaps)
        //{
        //    LightmapData lightmapData = new LightmapData();
        //    lightmapData.lightmapColor = texture2d;
        //    lightmapDataList.Add(lightmapData);
        //}
        //LightmapSettings.lightmaps = lightmapDataList.ToArray();
        ApplyRendererInfo(m_RendererInfo);
	}

	static void ApplyRendererInfo (RendererInfo[] infos)
	{
		for (int i=0;i<infos.Length;i++)
		{
			var info = infos[i];
			info.renderer.lightmapIndex = info.lightmapIndex;
			info.renderer.lightmapScaleOffset = info.lightmapOffsetScale;
		}
	}

#if UNITY_EDITOR
	[UnityEditor.MenuItem("Assets/Generate Lightmap Info")]
	public static void GenerateLightmapInfo ()
	{
		PrefabLightmapData[] prefabs = FindObjectsOfType<PrefabLightmapData>();

		foreach (var instance in prefabs)
		{
			var gameObject = instance.gameObject;
			var rendererInfos = new List<RendererInfo>();
            var lightmaps = new List<Texture2D>();

            GenerateLightmapInfo(gameObject, rendererInfos, lightmaps);
			
			instance.m_RendererInfo = rendererInfos.ToArray();
            //instance.m_Lightmaps = lightmaps.ToArray();

            var targetPrefab = UnityEditor.PrefabUtility.GetCorrespondingObjectFromSource(gameObject) as GameObject;
			if (targetPrefab != null)
			{
				UnityEditor.PrefabUtility.ReplacePrefab(gameObject, targetPrefab);
			}
		}
	}

	static void GenerateLightmapInfo (GameObject root, List<RendererInfo> rendererInfos, List<Texture2D> lightmaps)
	{
		var renderers = root.GetComponentsInChildren<MeshRenderer>();
		foreach (MeshRenderer renderer in renderers)
		{
            Debug.Log(renderer.name + " " + renderer.lightmapIndex);
			if (renderer.lightmapIndex != -1)
			{
				RendererInfo info = new RendererInfo();
				info.renderer = renderer;
				info.lightmapOffsetScale = renderer.lightmapScaleOffset;
				info.lightmapIndex = renderer.lightmapIndex;

				rendererInfos.Add(info);
			}
		}

        foreach (LightmapData data in LightmapSettings.lightmaps)
        {
            lightmaps.Add(data.lightmapColor);
        }

    }
#endif

}